import {useEffect, useState} from "react";
import prompt from "vendor/utils/prompt";
import {RespDataType,getRole, getRoleDeptCustomDataScope, updateRoleDataScope} from "../../../api";

export const useDataAuth = (roleId: number) => {
    const [ loading, setLoading ] = useState(true);
    const [ deptTree, setDeptTree] = useState<RealTreeNode[]>([]);
    const [ selectedDataScope, setSelectedDataScope ] = useState<string>();
    const [ selectedDeptIds, setSelectedDeptIds ] = useState<number[]>([]);

    useEffect(() => {
        setLoading(true);
        Promise.all([getRole(roleId), getRoleDeptCustomDataScope(roleId)]).then((resp) => {
            const [ roleResp, dataScopeResp ] = resp;

            setSelectedDataScope(roleResp.data.dataScope);
            setSelectedDeptIds(dataScopeResp.data.checkedKeys);
            setDeptTree(formatDeptTree(dataScopeResp.data.depts));
            setLoading(false);
        })
        // getRoleDeptCustomDataScope(roleId).then((resp) => {
        //     setSelectedDeptIds(resp.data.checkedKeys);
        //     setDeptTree(formatDeptTree(resp.data.depts));
        //     setLoading(false);
        // })
    }, [roleId]);


    const updateDataScope = (values: {dataScope: string, deptIds: number[]},successCallback: Function, failedCallback: Function) => {
        updateRoleDataScope(roleId, values).then(() => {
            prompt.success("授权成功");
            successCallback();
        }).catch(() => failedCallback())
    }

    return {loading, deptTree, selectedDataScope, setSelectedDataScope, selectedDeptIds, setSelectedDeptIds, updateDataScope}

}

interface RealTreeNode{
    title: string;
    key: number;
    value: number;
    children: RealTreeNode[];
}

const formatDeptTree = (tree: RespDataType.DeptTree): RealTreeNode[] => {
    return tree.map((item) => ({
        title: item.label,
        value: item.id,
        key: item.id,
        children: formatDeptTree(item.children || []),
    }))
}